package com.cyjt.operation.ui;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cyjt.operation.R;
import com.cyjt.operation.base.AppContext;
import com.cyjt.operation.base.BaseActivityWithNFC;
import com.cyjt.operation.base.HandlerMessageCodes;
import com.cyjt.operation.bean.DynamicNodes;
import com.cyjt.operation.bean.ParkingLot;
import com.cyjt.operation.fragment.DialogFragmentForBaseStationHeartBeats;
import com.cyjt.operation.fragment.DialogFragmentForDynamicSensorHeartBeats;
import com.cyjt.operation.uitools.CHexConver;
import com.cyjt.operation.uitools.CharacterTool2;
import com.cyjt.operation.uitools.HardwareInterfaceTools;
import com.cyjt.operation.view.ActionBarLayout;

/**
 * 点击动态交通车位列表项后跳转的部署Activity，主要功能是绑定动态节点
 * 
 * @author LTP
 * 
 */
public class DynamicParkingLotDeployActivity extends BaseActivityWithNFC implements OnClickListener {
	/** 显示基站的文本 */
	private TextView textView_dynamic_parking_lot_deploy_code;
	/** 显示节点的文本（当未绑定时可编辑） */
	private EditText editText_dynamic_parking_lot_deploy_nfc_code;
	/** 显示路口方向的文本 */
	private TextView textView_dynamic_parking_lot_deploy_crossing;
	/** 绑定动态节点的按键 */
	private Button button_dynamic_parking_lot_deploy_bound;
	/** 获取节点心跳的按键 */
	private Button button_dynamic_parking_lot_deploy_featch_nodes_hertbeat;
	/** 获取基站心跳的按键 */
	private Button button_dynamic_parking_lot_deploy_featch_base_station_hertbeat;
	/** Spinner下拉控件用于选择车道 */
	private Spinner spinner_dynamic_parking_lot_deploy_select_driveway, spinner_dynamic_parking_lot_node_fuction;
	private FragmentManager fragmentmanager;
	/** Spinner中选择的车道 */
	int selectDriveway;
	private String function;
	/** 动态节点的个数 */
	private int dynamicNodesSize;
	private DynamicNodes dynamicNodes;

	/** ==========蓝牙========== */
	private final static int REQUEST_CONNECT_DEVICE = 1; // 宏定义查询设备句柄

	private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; // SPP服务UUID号

	private InputStream is; // 输入流，用来接收蓝牙数据
	// private TextView text0; //提示栏解句柄
	private String smsg = ""; // 显示用数据缓存
	private String fmsg = ""; // 保存用数据缓存

	public String filename = ""; // 用来保存存储的文件名
	BluetoothDevice _device = null; // 蓝牙设备
	BluetoothSocket _socket = null; // 蓝牙通信socket
	boolean isSocket = false; // 判断是否连接蓝牙成功
	boolean _discoveryFinished = false;
	boolean bRun = true;
	boolean bThread = false;
	public ConnectedThread mConnectedThread;

	@SuppressLint("NewApi")
	private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter(); // 获取本地蓝牙适配器，即蓝牙设备

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HandlerMessageCodes.BOUND_DYNAMIC_NODES_SUCCEED:
				// 绑定动态节点成功
				Toast.makeText(DynamicParkingLotDeployActivity.this, "动态节点绑定成功", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMessageCodes.BOUND_DYNAMIC_NODES_FAILED:
				// 绑定动态节点失败
				Toast.makeText(DynamicParkingLotDeployActivity.this, "动态节点绑定失败", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dynamic_parking_lot_deploy);
		fragmentmanager = getFragmentManager();
		// 接收从动态交通车位的Activity传来的dynamicNodes实例
		dynamicNodes = (DynamicNodes) getIntent().getSerializableExtra("dynamicNodes");
		// 接收从动态交通车位的Activity传来的动态节点的个数
		dynamicNodesSize = getIntent().getIntExtra("dynamicNodesSize", 0);
		initView();
	}

	private void initView() {
		btn = (TextView) findViewById(R.id.textView_tips_bluetooth_status);
		// TODO Auto-generated method stub
		ActionBarLayout.setTitle("动态节点部署", Color.argb(255, 255, 136, 0));
		textView_dynamic_parking_lot_deploy_code = (TextView) findViewById(
				R.id.textView_dynamic_parking_lot_deploy_code);
		textView_dynamic_parking_lot_deploy_code.setText(dynamicNodes.getCode() + "");
		editText_dynamic_parking_lot_deploy_nfc_code = (EditText) findViewById(
				R.id.editText_dynamic_parking_lot_deploy_nfc_code);
		if (!"无绑定".equals(dynamicNodes.getNfcCode())) {
			editText_dynamic_parking_lot_deploy_nfc_code.setText(dynamicNodes.getNfcCode() + "");
		}
		textView_dynamic_parking_lot_deploy_crossing = (TextView) findViewById(
				R.id.textView_dynamic_parking_lot_deploy_crossing);
		textView_dynamic_parking_lot_deploy_crossing.setText(dynamicNodes.getCrossing() + "");
		button_dynamic_parking_lot_deploy_bound = (Button) findViewById(R.id.button_dynamic_parking_lot_deploy_bound);
		button_dynamic_parking_lot_deploy_bound.setOnClickListener(this);
		spinner_dynamic_parking_lot_deploy_select_driveway = (Spinner) findViewById(
				R.id.spinner_dynamic_parking_lot_deploy_select_driveway);
		spinner_dynamic_parking_lot_node_fuction = (Spinner) findViewById(
				R.id.spinner_dynamic_parking_lot_node_function);
		initSpinner();// 初始化Spinner
		initNodeFunctionSpinner();
		button_dynamic_parking_lot_deploy_featch_nodes_hertbeat = (Button) findViewById(
				R.id.button_dynamic_parking_lot_deploy_featch_nodes_hertbeat);
		button_dynamic_parking_lot_deploy_featch_nodes_hertbeat.setOnClickListener(this);
		button_dynamic_parking_lot_deploy_featch_base_station_hertbeat = (Button) findViewById(
				R.id.button_dynamic_parking_lot_deploy_featch_base_station_hertbeat);
		button_dynamic_parking_lot_deploy_featch_base_station_hertbeat.setOnClickListener(this);
	}

	/**
	 * 初始化Spinner
	 */
	private void initSpinner() {
		List<Integer> drivewayList = new ArrayList<Integer>();
		for (int i = 0; i < dynamicNodesSize; i++) {
			drivewayList.add(i + 1);
		}
		ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(DynamicParkingLotDeployActivity.this,
				android.R.layout.simple_spinner_item, drivewayList);
		spinner_dynamic_parking_lot_deploy_select_driveway.setAdapter(adapter);
		// if ("无绑定".equals(dynamicNodes.getDriveway())) {
		// spinner_dynamic_parking_lot_deploy_select_driveway
		// .setPrompt("请选择车道");
		// } else {
		// spinner_dynamic_parking_lot_deploy_select_driveway.setSelection(
		// dynamicNodes.getDriveway().charAt(0), true);
		// }
		spinner_dynamic_parking_lot_deploy_select_driveway.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				selectDriveway = (Integer) parent.getItemAtPosition(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
	}

	private String funcId;

	private void initNodeFunctionSpinner() {
		List<String> nodeFunctionList = new ArrayList<String>();
		nodeFunctionList.add("流量计数节点");
		nodeFunctionList.add("停车节点");
		nodeFunctionList.add("防堵死节点");
		nodeFunctionList.add("相位空节点");
		nodeFunctionList.add("排队节点");
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(DynamicParkingLotDeployActivity.this,
				android.R.layout.simple_spinner_item, nodeFunctionList);
		spinner_dynamic_parking_lot_node_fuction.setAdapter(adapter);
		spinner_dynamic_parking_lot_node_fuction.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				function = (String) arg0.getItemAtPosition(arg2);
				Log.i("demo", function);
				switch (arg2) {
				case 0:
					funcId = "CD";
					break;
				case 1:
					funcId = "C0";
					break;
				case 2:
					funcId = "C3";
					break;
				case 3:
					funcId = "C4";
					break;
				case 4:
					funcId = "C5";
					break;

				default:
					break;
				}
				Log.i("demo", "funcId=" + funcId);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button_dynamic_parking_lot_deploy_bound:
			// 绑定动态节点的点击事件
			String nfcCodeString = editText_dynamic_parking_lot_deploy_nfc_code.getText().toString();
			dynamicNodes.setNfcCode(nfcCodeString);
			dynamicNodes.setDriveway(selectDriveway);
			if (isSocket) {
				if (dynamicNodes.getNfcCode().equals("")) {
					Toast.makeText(DynamicParkingLotDeployActivity.this, "请将信息补充完整", Toast.LENGTH_SHORT).show();
					return;
				}
				sendMessage(HardwareInterfaceTools.getDynamicSubmitForConBaseStationMessage(dynamicNodes.getNfcCode(),
						dynamicNodes.getCode(), dynamicNodes.getCrossing()));
				// 提交
				AppContext.getInstance().getVolleyTools().boundDynamicNodes(handler, dynamicNodes);
			} else {
				Toast.makeText(DynamicParkingLotDeployActivity.this, "请先连接蓝牙在绑定", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.button_dynamic_parking_lot_deploy_featch_nodes_hertbeat:
			// 点击查看节点心跳信息
			DialogFragmentForDynamicSensorHeartBeats mDialogFragmentForSensorHeartBeats = new DialogFragmentForDynamicSensorHeartBeats();
			Bundle args = new Bundle();
			args.putString("sensorCode", dynamicNodes.getNfcCode());
			Log.d("LTP", dynamicNodes.getNfcCode());
			args.putBoolean("isCurrentLotActivited", true);
			mDialogFragmentForSensorHeartBeats.setArguments(args);
			mDialogFragmentForSensorHeartBeats.setStyle(DialogFragment.STYLE_NO_TITLE,
					android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth);
			mDialogFragmentForSensorHeartBeats.show(getFragmentManager(), "SensorHeartBeatsListDialogFragment");
			break;
		case R.id.button_dynamic_parking_lot_deploy_featch_base_station_hertbeat:
			// 点击查看基站心跳信息
			DialogFragmentForBaseStationHeartBeats mDialogFragmentForBaseStationHeartBeats = new DialogFragmentForBaseStationHeartBeats();
			Bundle args2 = new Bundle();
			args2.putString("baseStationCode", dynamicNodes.getCode());
			mDialogFragmentForBaseStationHeartBeats.setArguments(args2);
			mDialogFragmentForBaseStationHeartBeats.setStyle(DialogFragment.STYLE_NO_TITLE,
					android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth);
			mDialogFragmentForBaseStationHeartBeats.show(fragmentmanager, "BaseStationHeartBeatsListDialogFragment");
			break;

		default:
			break;
		}
	}

	private TextView btn;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE: // 连接结果，由DeviceListActivity设置返回
			// 响应返回结果
			if (resultCode == Activity.RESULT_OK) { // 连接成功，由DeviceListActivity设置返回
				// MAC地址，由DeviceListActivity设置返回
				Log.i("demo", "DeviceListActivity设置返回+++++");
				String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
				// 得到蓝牙设备句柄
				_device = _bluetooth.getRemoteDevice(address);

				// 用服务号得到socket
				try {
					_socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
					mConnectedThread = new ConnectedThread(_socket);
				} catch (IOException e) {
					Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
					isSocket = false;
				}
				// 连接socket
				try {
					_socket.connect();
					Toast.makeText(this, "连接" + _device.getName() + "成功！", Toast.LENGTH_SHORT).show();
					btn.setText("断开");
					isSocket = true;
				} catch (IOException e) {
					try {
						Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
						_socket.close();
						_socket = null;
						isSocket = false;
					} catch (IOException ee) {
						Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
						isSocket = false;
					}

					return;
				}

				// 打开接收线程
				try {
					is = _socket.getInputStream(); // 得到蓝牙数据输入流
				} catch (IOException e) {
					Toast.makeText(this, "接收数据失败！", Toast.LENGTH_SHORT).show();
					return;
				}
				if (bThread == false) {
					ConnectedThread r;
					mConnectedThread.start();
					bThread = true;
				} else {
					bRun = true;
				}
			}
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	// 连接按键响应函数
	@SuppressLint("NewApi")
	public void onConnectButtonClicked(View v) {
		if (_bluetooth.isEnabled() == false) { // 如果蓝牙服务不可用则提示
			Toast.makeText(this, " 打开蓝牙中...", Toast.LENGTH_LONG).show();
			BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			mBluetoothAdapter.enable();
			return;
		}

		// 如未连接设备则打开DeviceListActivity进行设备搜索
		TextView btn = (TextView) findViewById(R.id.textView_tips_bluetooth_status);
		if (_socket == null) {
			Intent serverIntent = new Intent(this, DeviceListActivity.class);
			// // 跳转程序设置
			startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); //
		} else {
			// 关闭连接socket
			try {

				is.close();
				_socket.close();
				_socket = null;
				bRun = false;
				btn.setText("连接");
			} catch (IOException e) {
			}
		}
		return;
	}

	private class ConnectedThread extends Thread {
		private final BluetoothSocket mmSocket;
		private final InputStream mmInStream;
		private final OutputStream mmOutStream;

		public ConnectedThread(BluetoothSocket socket) {
			mmSocket = socket;
			InputStream tmpIn = null;
			OutputStream tmpOut = null;
			// 获得蓝牙通信需要的输入输出流
			try {
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
			} catch (IOException e) {

			}
			mmInStream = tmpIn;
			mmOutStream = tmpOut;
		}

		public void run() {
			byte[] buffer = new byte[1024];
			byte[] bu_temp = new byte[1024];
			int bytes;
			int bytes_temp = 0;
			// 在连接了之后保持对输入的监听
			// 这里使用死循环一直等待并接收数据
			try {
				while ((bytes = mmInStream.read(buffer, 0, 1024)) > -1) {

					// 得到输入的数据
					// bytes = mmInStream.read(buffer);
					Log.v("demo", "数据尺寸：" + bytes);
					// 将接收到的数据返回给 UI Activity
					bytes_temp += bytes;
					for (int i = bytes_temp - bytes; i < bytes_temp; i++) {
						bu_temp[i] = buffer[i - (bytes_temp - bytes)];
					}
					// if (bytes_temp == 12) {
					// if (CHexConver.byte2HexStr(bu_temp,
					// bytes_temp).startsWith("AA220000"))
					// mHandler.obtainMessage(HandlerCode.BLUETOOTH_MESSAGE_READED_STREAM,
					// CHexConver.byte2HexStr(bu_temp,
					// bytes_temp)).sendToTarget();
					// bytes_temp = 0;
					// }
					String s = CHexConver.byte2HexStr(bu_temp, bytes_temp).replace(" ", "");
					Log.v("demo", "数据累计:" + s);
					if (s.length() > 12 && (s.split("AA220000", 2).length > 1)) {
						s = s.split("AA220000", 2)[1];
						if (s.length() >= 16) {
							s = s.substring(0, 16);
							Log.v("demo", "数据解析:" + s);
							handler1.obtainMessage(1000, "AA220000" + s).sendToTarget();
							bytes_temp = 0;
						}
					}
				}
			} catch (IOException e) {
				// connectionLost();
				// // 出问题后从连接监听重新开始
				// BluetoothChatService.this.start();
			}

		}

		/**
		 * 朝连接上的设备发送数据
		 * 
		 * @param message
		 *            要发送的数据
		 */
		public void write(String message) {
			try {
				byte[] buffer = CharacterTool2.HexString2Bytes(message);
				mmOutStream.write(buffer);
				// 将已经发送完成的数据返回给 UI Activity
				handler1.obtainMessage(1001, CHexConver.byte2HexStr(buffer, buffer.length)).sendToTarget();
			} catch (IOException e) {

			}
		}

		public void cancel() {
			try {
				mmInStream.close();
				mmOutStream.close();
				mmSocket.close();
			} catch (IOException e) {

			}
		}
	}

	// 蓝牙消息处理队列
	Handler handler1 = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Log.i("demo", "smsg=" + smsg); // 显示数据
			// sv.scrollTo(0, dis.getMeasuredHeight()); // 跳至数据最后一页
			switch (msg.what) {
			case 1000:
				Toast.makeText(DynamicParkingLotDeployActivity.this, "READED:" + msg.obj, Toast.LENGTH_SHORT).show();
				DynamicParkingLotDeployActivity.this.handlerBluetoothMessageReaded((String) msg.obj);
				break;
			case 1001:
				Toast.makeText(DynamicParkingLotDeployActivity.this, "WRITED:" + msg.obj, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		}
	};

	private void handlerBluetoothMessageReaded(String message) {
		// TODO 处理部署基站发送的指令
		switch (HardwareInterfaceTools.HandlerResponseMessage(message)) {
		case 0:
			// ParkingSpa p = new ParkingSpa();
			// p.setNfc(HardwareInterfaceTools.HandlerResponseMessageContext(message));
			// Toast.makeText(MainActivity.this,"节点正在保存！",Toast.LENGTH_SHORT).show();
			// fragment_sen.upParkingSensorStatus(p,
			// AppContext.getInstance().getSpTools().readIntPreferences(SharedPreferencesTools.BINDING_INDEX_TABLE,
			// p.getNfc()));
			break;
		case 1:
			ParkingLot p = new ParkingLot();
			p.setSensorCode(HardwareInterfaceTools.HandlerResponseMessageContext(message));
			Toast.makeText(DynamicParkingLotDeployActivity.this, p.getSensorCode(), Toast.LENGTH_SHORT).show();
			Toast.makeText(DynamicParkingLotDeployActivity.this, "节点：" + p.getNfcCode() + " 设置成功！", Toast.LENGTH_SHORT)
					.show();
			sendMessage(message);
			bindingFinished(p, 0);
			break;
		default:
			break;
		}
	}

	/**
	 * 使用非同步的方式写数据
	 * 
	 * @param message
	 *            要写出的数据
	 */
	public void sendMessage(String message) {
		// 创建一个临时对象
		ConnectedThread r;
		// 同步同一个ConnectedThread对象
		synchronized (this) {
			r = mConnectedThread;
		}
		// 执行写不同步
		r.write(message);
	}

	/**
	 * 蓝牙返回绑定成功的信息后会执行该方法通知UI更新
	 */
	private void bindingFinished(ParkingLot parkingSpa, int index) {
		// fragment_sen.upParkingSensorStatusFinished(parkingSpa, index);
		setResult(15);
		onBackPressed();
	}
}
